package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;

import com.ruoyi.system.domain.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.weixin.WeixinUtil;
import com.ruoyi.common.utils.weixin.po.AccessToken;
import com.ruoyi.common.utils.weixin.po.AccessUser;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.system.service.IWeixinService;

/**
 * 微信模块管理
 * @author admin
 *
 */
@Controller
@RequestMapping("/system/wxCode")
public class WxCodeController extends BaseController{
	
	private String prefix = "system/wxcode";

	@Autowired
	private IWeixinService weixinService;

	/**
	 * 视图页面展示
	 * @return
	 */
	@RequiresPermissions("system:wxCode:view")
    @GetMapping()
    public String index(){
        return prefix + "/wxcode";
    }
	
	/**
	 * 微信号列表页数据
	 * @param wxCode
	 * @return
	 */
	@RequiresPermissions("system:wxCode:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxCode wxCode){
        startPage();
        List<WxCode> list = weixinService.selectWxCodeList(wxCode);
        for (WxCode code: list) {
            if(code.getErrCode() != null){
                WxErrCompare errCompare = weixinService.selectWxErrCompareByErrCode(String.valueOf(code.getErrCode()));
                if(errCompare != null){
                    //String errMsg = WeixinUtil.ErrCodeConvertErrMsg(code.getErrCode());
                    String errMsg = errCompare.getErrMsg();
                    code.setErrMsg(errMsg);
                }
            }
        }
        return getDataTable(list);
    }
	
	/**
	 * 添加微信号
	 * @return
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
     * 新增保存微信号
     */
    @RequiresPermissions("system:wxCode:add")
    @Log(title = "微信号管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(WxCode wxCode){
    	wxCode.setCreateAt(new Date());
    	// 获取token
        AccessToken accessToken = WeixinUtil.getAccessToken(wxCode.getAppId(),wxCode.getAppSecret());
        if(accessToken != null ){
            // 保存token
            wxCode.setAccessToken(accessToken.getToken());
            wxCode.setExpiresIn(accessToken.getExpiresIn());
            // 获取失败
            wxCode.setErrCode(accessToken.getErrcode());
            wxCode.setErrMsg(accessToken.getErrmsg());
        }

        return toAjax(weixinService.insertWxCode(wxCode));
    }

	/**
	 * 修改微信号
	 */
	@GetMapping("/edit/{wxId}")
	public String edit(@PathVariable("wxId") Long wxId, ModelMap mmap)
	{
		mmap.put("wxCode", weixinService.getEntityById(wxId));
		return prefix + "/edit";
	}


	/**
	 * 修改保存微信号
	 */
	@RequiresPermissions("system:wxCode:edit")
	@Log(title = "微信号管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public AjaxResult editSave(WxCode wxCode){
        // 获取token
        AccessToken accessToken = WeixinUtil.getAccessToken(wxCode.getAppId(),wxCode.getAppSecret());
        if(accessToken != null ){
            // 保存token
            wxCode.setAccessToken(accessToken.getToken());
            wxCode.setExpiresIn(accessToken.getExpiresIn());
            // 获取失败
            wxCode.setErrCode(accessToken.getErrcode());
            wxCode.setErrMsg(accessToken.getErrmsg());
        }
	    return toAjax(weixinService.updateWxCode(wxCode));
	}

    @RequiresPermissions("system:wxCode:remove")
    @Log(title = "微信号管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        try{
            return toAjax(weixinService.deleteWxCodeByIds(ids));
        } catch (Exception e){ return error(e.getMessage()); }
    }
    
    /**
     * 获取微信号关注用户 
     * @param appId
     * @param appSecret
     * @return
     * @throws Exception 
     */
    @PostMapping("/concernUsers")
    @ResponseBody
    public AjaxResult getConcernUserUrl(String appId,String appSecret) throws Exception{
		AccessToken accessToken = WeixinUtil.getAccessToken(appId, appSecret);
    	if(accessToken != null) {
    		// 根据  appId 获取 WxCode
    		WxCode code = weixinService.getEntityByAppId(appId);
    		// 根据 accessToken 获取关注用户信息
    		List<AccessUser> accessUsers = WeixinUtil.getAccessUsers(accessToken.getToken());
    		for(AccessUser accessUser : accessUsers) {
    			// 获取用户的详细信息
    			WxUser wxUser = weixinService.getWxUserByAccessUser(accessToken.getToken(), accessUser.getOpenid());
    			if(code != null) {
    				wxUser.setWxCode(code.getWxCode());
    				wxUser.setWxName(code.getWxName());
        		}
    			// 插入微信用户
    			weixinService.insertWxUser(wxUser);
    		}
    		return toAjax(1);
    	}else return toAjax(0);
    }
    
	/**
     * 校验微信号名称
     */
    @PostMapping("/checkWxCodeUnique")
    @ResponseBody
    public String checkWxCodeUnique(WxCode wxCode){
        return weixinService.checkWxCodeUnique(wxCode);
    }

}
